<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;

/**
 * 公共接口
 */
class Common extends Api
{

    protected $noNeedLogin = ['init','getwechatsignpackage'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');
            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => Config::get('upload'),
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     *
     * @param File $file 文件流
     */
    public function upload()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id'    => 0,
                'user_id'     => (int)$this->auth->id,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            $this->success(__('Upload successful'), [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }


    public function base64imgsave(){
        $img = $this->request->request('file');

        //文件夹日期
        $ymd = date("Ymd");

        //图片路径地址
        $basedir = 'uploads/'.$ymd.'';

        $fullpath = $basedir;
        if(!is_dir($fullpath)){
            mkdir($fullpath,0777,true);
        }
        $types = array('jpg', 'gif', 'png', 'jpeg');

        $img = str_replace(array('_','-'), array('/','+'), $img);

        $b64img = substr($img, 0,100);

        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $b64img, $matches))
        {

            $type = $matches[2];
            if(!in_array($type, $types))
            {

                $this->error(__('图片格式不正确，只支持 jpg、gif、png、jpeg'));
            }
            $img = str_replace($matches[1], '', $img);
            $img = base64_decode($img);
            $photo = '/'.md5(date('YmdHis').rand(1000, 9999)).'.'.$type;
            file_put_contents($fullpath.$photo, $img);


            $imgpath = '/' . $basedir.$photo;

            //压缩
            $uploadImagePath = './'.$basedir.$photo;
            $image = \think\Image::open($uploadImagePath);
// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
            $image->thumb(750,750,\think\Image::THUMB_SCALING)->save($uploadImagePath);
            $this->success(__('图片上传成功'),$imgpath);

        }


        $this->error(__('请选择要上传的图片'));

    }

    public function sendSms(){
        $mobile = $this->request->post('mobile');
        $event = $this->request->post('event');

        $result = send_sms($mobile,$event);
        // return json($result);
        if($result['code'] == 1){
            $this->success($result['msg']);

        }else{
            $this->error($result['msg']);
        }
    }

    public function checkCode(){
        $mobile = $this->request->post('mobile/d');
        $code = $this->request->post('code/d');
        $event = $this->request->post('event');

        $smsLogic = new \app\common\model\SmsLogic();
        $result = $smsLogic->checkCode($mobile,$code,$event);
        // return json($result);
        if($result['code'] == 1){
            $this->success($result['msg']);

        }else{
            $this->error($result['msg']);
        }

    }

    public function sendSmsNotice(){
        $mobile = $this->request->post('mobile/d');
        $content = $this->request->post('content');

        $result = sms_notice($mobile,$content);
        if($result['code'] == 1){
            $this->success($result['msg']);

        }else{
            $this->error($result['msg']);
        }
    }

    public function getWechatSignPackage(){

        $url = $this->request->request('url');
        $wechatObj = new \wechat\Wechat();
//        dump($wechatObj);
        $res = $wechatObj->getSignPackage($url);

        $this->success('',$res);
    }



}
